/*
 *  Copyright (C) 2005-2007 Renier Roth
 *  www.renier.de
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package de.renier.vdr.channel.editor.container;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 * AbstractListTransferHandler
 * 
 * @author <a href="mailto:editor@renier.de">Renier Roth</a>
 */
public abstract class AbstractListTransferHandler implements DragGestureListener, DragSourceListener,
    DropTargetListener {

  private DNDList list;
  private DragSource dragSource; // dragsource
  private Rectangle rect2D = new Rectangle();
  private boolean drawImage;

  protected AbstractListTransferHandler(DNDList list, int action, boolean drawIcon) {
    this.list = list;
    drawImage = drawIcon;
    dragSource = new DragSource();
    dragSource.createDefaultDragGestureRecognizer(list, action, this);
    new DropTarget(list, action, this);
  }

  /* Methods for DragSourceListener */
  public void dragDropEnd(DragSourceDropEvent dsde) {
    if (dsde.getDropSuccess() && dsde.getDropAction() == DnDConstants.ACTION_MOVE) {
      try {
        Transferable transferable = dsde.getDragSourceContext().getTransferable();
        DefaultMutableTreeNode draggedNode = (DefaultMutableTreeNode) transferable
            .getTransferData(TransferableNode.NODE_FLAVOR);
        ;
        afterDrop(list, draggedNode, dsde.getDropAction());
        list.setSelectedValue(draggedNode, true);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public final void dragEnter(DragSourceDragEvent dsde) {
    int action = dsde.getDropAction();

    if (action == DnDConstants.ACTION_MOVE) {
      dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
    } else {
      dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
    }

  }

  public final void dragOver(DragSourceDragEvent dsde) {
    int action = dsde.getDropAction();

    if (action == DnDConstants.ACTION_MOVE) {
      dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
    } else {
      dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
    }
  }

  public final void dropActionChanged(DragSourceDragEvent dsde) {
    int action = dsde.getDropAction();

    if (action == DnDConstants.ACTION_MOVE) {
      dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
    } else {
      dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
    }

  }

  public final void dragExit(DragSourceEvent dse) {
    dse.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
  }

  /* Methods for DragGestureListener */
  public final void dragGestureRecognized(DragGestureEvent dge) {
    DefaultMutableTreeNode draggedNode = (DefaultMutableTreeNode) list.getSelectedValue();
    int selectedIndex = list.getSelectedIndex();

    if (drawImage) {
      Rectangle pathBounds = list.getCellBounds(selectedIndex, selectedIndex);
      // returning the label
      JComponent lbl = (JComponent) list.getCellRenderer().getListCellRendererComponent(list, draggedNode,
                                                                                        selectedIndex, false, false);
      // setting bounds to lbl
      lbl.setBounds(pathBounds);
      // buffered image the label's ht and width
      TransferableNode.image = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
          java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE);
      // creating the graphics for buffered image
      Graphics2D graphics = TransferableNode.image.createGraphics();
      // Sets the Composite for the Graphics2D context
      graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
      // painting the graphics to label
      lbl.paint(graphics);
      graphics.dispose();
    }
    dragSource.startDrag(dge, DragSource.DefaultMoveNoDrop, TransferableNode.image, new Point(0, 0),
                         new TransferableNode(draggedNode, null), this);

  }

  /* Methods for DropTargetListener */

  public final void dragEnter(DropTargetDragEvent dtde) {
    Point pt = dtde.getLocation();
    int action = dtde.getDropAction();
    if (drawImage) {
      paintImage(pt);
    }
    try {
      if (canPerformAction(list, TransferableNode.draggedNode, action, pt)) {
        dtde.acceptDrag(action);
      } else {
        dtde.rejectDrag();
      }
    } catch (Exception e) {
      dtde.rejectDrag();
    }
  }

  public final void dragExit(DropTargetEvent dte) {
    if (drawImage) {
      clearImage();
    }
  }

  public final void dragOver(DropTargetDragEvent dtde) {
    Point pt = dtde.getLocation();
    int action = dtde.getDropAction();
    list.autoscroll(pt);
    if (drawImage) {
      paintImage(pt);
    }
    try {
      if (canPerformAction(list, TransferableNode.draggedNode, action, pt)) {
        dtde.acceptDrag(action);
      } else {
        dtde.rejectDrag();
      }
    } catch (Exception e) {
      dtde.rejectDrag();
    }
  }

  public final void dropActionChanged(DropTargetDragEvent dtde) {
    Point pt = dtde.getLocation();
    int action = dtde.getDropAction();
    if (drawImage) {
      paintImage(pt);
    }
    try {
      if (canPerformAction(list, TransferableNode.draggedNode, action, pt)) {
        dtde.acceptDrag(action);
      } else {
        dtde.rejectDrag();
      }
    } catch (Exception e) {
      dtde.rejectDrag();
    }
  }

  public final void drop(DropTargetDropEvent dtde) {
    try {
      if (drawImage) {
        clearImage();
      }
      int action = dtde.getDropAction();
      Transferable transferable = dtde.getTransferable();
      DefaultMutableTreeNode draggedNode = (DefaultMutableTreeNode) transferable
          .getTransferData(TransferableNode.NODE_FLAVOR);
      Point pt = dtde.getLocation();
      if (transferable.isDataFlavorSupported(TransferableNode.NODE_FLAVOR)
          && canPerformAction(list, draggedNode, action, pt)) {
        int newPosition = list.locationToIndex(pt);
        if (executeDrop(list, draggedNode, newPosition, action)) {
          dtde.acceptDrop(action);
          dtde.dropComplete(true);
          return;
        }
      }
      dtde.rejectDrop();
      dtde.dropComplete(false);
    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
      dtde.rejectDrop();
      dtde.dropComplete(false);
    }
  }

  private final void paintImage(Point pt) {
    list.paintImmediately(rect2D.getBounds());
    rect2D.setRect((int) pt.getX(), (int) pt.getY(), TransferableNode.image.getWidth(), TransferableNode.image
        .getHeight());
    list.getGraphics().drawImage(TransferableNode.image, (int) pt.getX(), (int) pt.getY(), list);
  }

  private final void clearImage() {
    list.paintImmediately(rect2D.getBounds());
  }

  public abstract boolean canPerformAction(DNDList target, DefaultMutableTreeNode draggedNode, int action,
      Point location);

  public abstract boolean executeDrop(DNDList target, DefaultMutableTreeNode draggedNode, int newPosition, int action);

  public abstract void afterDrop(DNDList dndList, DefaultMutableTreeNode draggedNode, int action);
}